<template>
  <view class="container">
    <!-- 收货地址 -->
    <view class="address-section" @tap="chooseAddress">
      <view class="address-icon">📍</view>
      <block v-if="address">
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{address.receiverName}}</text>
            <text class="phone">{{address.phoneNumber}}</text>
            <text class="tag" v-if="address.isDefault">默认</text>
          </view>
          <view class="address-detail">
            {{address.provinceName}}{{address.cityName}}{{address.districtName}}{{address.detailedAddress}}
          </view>
        </view>
      </block>
      <view v-else class="no-address">
        <text class="add-address">请选择收货地址</text>
      </view>
      <text class="arrow">></text>
    </view>
    
    <!-- 商品列表 -->
    <view class="goods-section">
      <view class="section-title">商品信息</view>
      <view class="goods-list">
        <view class="goods-item" v-for="item in orderGoods" :key="item.id">
          <image class="goods-image" :src="item.image" mode="aspectFill"></image>
          <view class="goods-info">
            <view class="goods-name">{{item.productName}}</view>
            <view class="goods-specs">规格：{{item.specifications}}</view>
            <view class="price-quantity">
              <text class="price">¥{{item.price}}</text>
              <text class="quantity">x{{item.quantity}}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="goods-summary">
        <view class="summary-item">
          <text>共{{orderGoods.length}}件商品</text>
          <text>小计：¥{{totalPrice}}</text>
        </view>
      </view>
    </view>
    
    <!-- 配送方式 -->
    <view class="delivery-section">
      <view class="section-title">配送方式</view>
      <view class="delivery-info">
        <text class="label">快递配送</text>
        <view class="value">
          <text>快递费</text>
          <text class="freight">¥{{freight}}</text>
        </view>
      </view>
    </view>
    
    <!-- 订单备注 -->
    <view class="remark-section">
      <view class="section-title">订单备注</view>
      <input 
        class="remark-input" 
        type="text" 
        v-model="remark" 
        placeholder="选填：请填写其他需求（45字以内）"
        maxlength="45"
      />
    </view>
    
    <!-- 订单金额 -->
    <view class="amount-section">
      <view class="amount-item">
        <text class="label">商品金额</text>
        <text class="value">¥{{totalPrice}}</text>
      </view>
      <view class="amount-item">
        <text class="label">运费</text>
        <text class="value">¥{{freight}}</text>
      </view>
      <view class="amount-item total">
        <text class="label">实付金额</text>
        <text class="value price">¥{{actualPrice}}</text>
      </view>
    </view>
    
    <!-- 底部提交栏 -->
    <view class="footer">
      <view class="total-box">
        <text>实付金额：</text>
        <text class="price">¥{{actualPrice}}</text>
      </view>
      <button class="submit-btn" @tap="submitOrder" :disabled="!address">
        提交订单
      </button>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api'

export default {
  data() {
    return {
      orderGoods: [], // 订单商品列表
      address: null, // 收货地址
      remark: '', // 备注
      freight: 0, // 运费
      fromPage: '' // 来源页面：cart-购物车，detail-商品详情
    }
  },
  computed: {
    // 商品总价
    totalPrice() {
      return this.orderGoods.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0).toFixed(2)
    },
    // 实付金额（商品总价 + 运费）
    actualPrice() {
      return (Number(this.totalPrice) + this.freight).toFixed(2)
    }
  },
  onLoad(options) {
    // 解析传入的商品数据
    if (options.orderData) {
      const orderData = JSON.parse(decodeURIComponent(options.orderData))
      // 统一处理数组格式的商品数据
      this.orderGoods = orderData.map(item => ({
        cartId: item.cartId, // 保存购物车ID
        productId: item.productId,
        productName: item.productName,
        skuId: item.skuId,
        quantity: item.quantity,
        price: Number(item.price).toFixed(2),
        specifications: item.specifications,
        image: item.image || '/static/images/default-product.png'
      }))
      this.fromPage = options.type
      console.log('处理后的订单商品数据:', this.orderGoods)
    }
    // 加载默认收货地址
    this.loadDefaultAddress()
  },
  methods: {
    // 加载默认收货地址
    async loadDefaultAddress() {
      try {
        const { data } = await userApi.getAddress()
        if (Array.isArray(data) && data.length > 0) {
          // 获取默认地址或第一个地址
          this.address = data.find(addr => addr.isDefault === 1) || data[0]
        }
      } catch (error) {
        console.error('获取收货地址失败:', error)
        uni.showToast({
          title: '获取地址失败',
          icon: 'none'
        })
      }
    },
    
    // 选择收货地址
    chooseAddress() {
      uni.navigateTo({
        url: '/pages/address/list/index?select=true',
        events: {
          // 监听选择地址事件
          addressSelected: (address) => {
            console.log('选择的地址:', address)
            this.address = address
          }
        },
        success: (res) => {
          // 向打开的页面发送选择模式标志
          res.eventChannel.emit('mode', { select: true })
        }
      })
    },
    
    // 页面显示时触发
    onShow() {
      console.log('订单页面显示')
    },
    
    // 提交订单
    async submitOrder() {
      if (!this.address) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '提交中...'
        })

        let result
        if (this.fromPage === 'detail') {
          // 直接购买
          const item = this.orderGoods[0]
          const orderParams = {
            productId: item.productId,
            productName: item.productName,
            skuId: item.skuId,
            quantity: item.quantity,
            price: item.price,
            specifications: item.specifications,
            addressId: this.address.id,
            payMethod: 1,
            remark: this.remark || '直接下单'
          }
          result = await userApi.createDirectOrder(orderParams)
        } else {
          // 购物车下单
          const orderParams = {
            cartIds: this.orderGoods.map(item => item.cartId), // 使用购物车ID列表
            addressId: this.address.id,
            payMethod: 1,
            remark: this.remark || '购物车下单'
          }
          console.log('购物车下单参数:', orderParams)
          result = await userApi.createCartOrder(orderParams)
        }
        
        console.log('创建订单返回结果:', result)
        
        uni.hideLoading()
        uni.showToast({
          title: '订单创建成功',
          icon: 'success'
        })

        // 跳转到支付页面
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/order/pay/index?orderNo=${result.orderNo}&amount=${result.totalPrice}&createTime=${result.createTime}`
          })
        }, 1500)
        
      } catch (error) {
        console.error('提交订单失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '提交订单失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

/* 地址样式 */
.address-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  position: relative;
}

.address-section::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 6rpx;
  background: linear-gradient(45deg, #4caf50 25%, transparent 25%),
              linear-gradient(-45deg, #4caf50 25%, transparent 25%),
              linear-gradient(45deg, transparent 75%, #4caf50 75%),
              linear-gradient(-45deg, transparent 75%, #4caf50 75%);
  background-size: 20rpx 20rpx;
  background-position: 0 0, 0 10rpx, 10rpx -10rpx, -10rpx 0;
}

.address-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.address-info {
  flex: 1;
}

.user-info {
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
}

.name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-right: 20rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.tag {
  font-size: 20rpx;
  color: #4caf50;
  border: 1rpx solid #4caf50;
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.no-address {
  flex: 1;
}

.add-address {
  font-size: 28rpx;
  color: #666;
}

.arrow {
  font-size: 32rpx;
  color: #999;
  margin-left: 20rpx;
}

/* 商品列表样式 */
.goods-section {
  background: #fff;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.goods-list {
  padding: 0 30rpx;
}

.goods-item {
  display: flex;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  background: #f5f5f5;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
}

.goods-specs {
  font-size: 24rpx;
  color: #666;
  margin: 10rpx 0;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #4caf50;
  font-weight: bold;
}

.quantity {
  font-size: 26rpx;
  color: #999;
}

.goods-summary {
  padding: 20rpx 30rpx;
  background: #fafafa;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
}

/* 配送方式样式 */
.delivery-section {
  background: #fff;
  margin-bottom: 20rpx;
}

.delivery-info {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delivery-info .label {
  font-size: 28rpx;
  color: #333;
}

.delivery-info .value {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
}

.freight {
  color: #4caf50;
  margin-left: 10rpx;
}

/* 备注样式 */
.remark-section {
  background: #fff;
  margin-bottom: 20rpx;
}

.remark-input {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
}

/* 订单金额样式 */
.amount-section {
  background: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.amount-item:last-child {
  margin-bottom: 0;
}

.amount-item.total {
  border-top: 1rpx solid #f5f5f5;
  padding-top: 20rpx;
  margin-top: 20rpx;
}

.amount-item .label {
  font-size: 28rpx;
  color: #666;
}

.amount-item .value {
  font-size: 28rpx;
  color: #333;
}

.amount-item .value.price {
  color: #4caf50;
  font-size: 32rpx;
  font-weight: bold;
}

/* 底部提交栏样式 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-box {
  flex: 1;
  display: flex;
  align-items: baseline;
  font-size: 28rpx;
  color: #333;
}

.total-box .price {
  font-size: 36rpx;
  color: #4caf50;
  font-weight: bold;
}

.submit-btn {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #4caf50, #66bb6a);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-left: 30rpx;
  font-weight: bold;
}

.submit-btn[disabled] {
  background: #ccc;
  color: #fff;
}
</style> 